package com.usian.comment.service.impl;


import com.usian.comment.feign.UserFeign;
import com.usian.comment.service.CommentRepayService;
import com.usian.common.exception.CatchCustomException;
import com.usian.common.exception.code.UserStatusCode;
import com.usian.model.comment.dtos.CommentRepayDto;
import com.usian.model.comment.dtos.CommentRepayLikeDto;
import com.usian.model.comment.dtos.CommentRepaySaveDto;
import com.usian.model.comment.pojos.ApComment;
import com.usian.model.comment.pojos.ApCommentRepay;
import com.usian.model.comment.pojos.ApCommentRepayLike;
import com.usian.model.comment.vos.ApCommentRepayVo;
import com.usian.model.common.dtos.ResponseResult;
import com.usian.model.common.enums.AppHttpCodeEnum;
import com.usian.model.user.pojos.ApUser;
import com.usian.utils.common.SnowflakeIdWorker;
import com.usian.utils.threadlocal.AppThreadLocalUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

@Service
public class CommentRepayServiceImpl implements CommentRepayService {

    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private UserFeign userFeign;

    @Autowired
    private SnowflakeIdWorker snowflakeIdWorker;

    @Override
    public ResponseResult loadCommentRepay(CommentRepayDto dto) {
        //1.检查参数  评论Id
        if(dto.getCommentId() == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        int size = 10; //默认展示10条 回复评论
        Query query = new Query(Criteria.where("commentId").is(dto.getCommentId()).and("createdTime").lt(dto.getMinDate()));
        query.limit(size);
        query.with(Sort.by(Sort.Direction.DESC,"createdTime"));

        List<ApCommentRepay> list =  mongoTemplate.find(query, ApCommentRepay.class);
        ApUser user = AppThreadLocalUtils.getUser();
        if(user== null){
            return ResponseResult.okResult(list);
        }
        //list.stream().map(x->{return x.getId();}).collect(Collectors.toList());
        List<String> idList = list.stream().map(x->x.getId()).collect(Collectors.toList());
        // 查询评论点赞数据
        Query query1 = Query.query(Criteria.where("commentRepayId").in(idList).and("authorId").is(user.getId()));
        List<ApCommentRepayLike> apCommentRepayLikes = mongoTemplate.find(query1, ApCommentRepayLike.class);
        List<ApCommentRepayVo> apCommentRepayVoList = new ArrayList<>();
        //封装点赞信息
        if(list!=null && apCommentRepayLikes != null) {
            list.stream().forEach(x -> {
                ApCommentRepayVo apCommentRepayVo = new ApCommentRepayVo();
                BeanUtils.copyProperties(x, apCommentRepayVo);
                for (ApCommentRepayLike apCommentRepayLike : apCommentRepayLikes) {
                    if (apCommentRepayLike.getCommentRepayId() == x.getId()) {
                        apCommentRepayVo.setOperation((short) 0);
                        break;
                    }
                    apCommentRepayVoList.add(apCommentRepayVo);
                }
            });
            return ResponseResult.okResult(apCommentRepayVoList);
        }else {
            return ResponseResult.okResult(list);
        }
    }

    @Override
    public ResponseResult saveCommentRepay(CommentRepaySaveDto dto) {
        if(dto==null){
            CatchCustomException.catchs(UserStatusCode.PARAM_FAIL,"参数非法");
        }
        if (dto.getContent() != null && dto.getContent().length() > 140) {
            CatchCustomException.catchs(UserStatusCode.PARAM_FAIL,"评论内容不能超过140字");
        }

        //用户登录
        ApUser apUser =  AppThreadLocalUtils.getUser();
        if(apUser==null){
            //没登录
            CatchCustomException.catchs(UserStatusCode.PARAM_FAIL,"用户没有登录");
        }
        apUser =  userFeign.findUserById(apUser.getId());
        if(apUser == null){
            CatchCustomException.catchs(UserStatusCode.PARAM_FAIL,"评论用户账户出现问题");
        }
        // 1. 保存回复数据
        ApCommentRepay apCommentRepay = new ApCommentRepay();
        apCommentRepay.setId(snowflakeIdWorker.nextId()+"");
        apCommentRepay.setAuthorId(apUser.getId());
        apCommentRepay.setAuthorName(apUser.getName());
        apCommentRepay.setLikes(0); // 喜欢
        apCommentRepay.setCommentId(dto.getCommentId());
        apCommentRepay.setContent(dto.getContent());
        apCommentRepay.setCreatedTime(new Date());
        apCommentRepay.setUpdatedTime(new Date());
        mongoTemplate.insert(apCommentRepay);
        // 2. 修改被回复的数据的回复数
        // 2.1 先查询 等到评论数据  然后通过save方法修改
        // 2.2 直接使用修改方法
        ApComment apComment =  mongoTemplate.findById(dto.getCommentId(), ApComment.class);
        apComment.setReply(apComment.getReply()+1);
        mongoTemplate.save(apComment);
        //mongoTemplate.updateFirst(Query.query(Criteria.where("commentId").is(dto.getCommentId())), Update.update("reply",apComment.getReply()+1),ApComment.class);
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    @Override
    public ResponseResult saveCommentRepayLike(CommentRepayLikeDto dto) {
        //1.检查参数
        if (dto.getCommentRepayId() == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        // 获取登录用户信息
        //2.判断是否登录
        ApUser user = AppThreadLocalUtils.getUser();
        if (user == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        // 先查询 回复评论数据
        ApCommentRepay apCommentRepay = mongoTemplate.findById(dto.getCommentRepayId(), ApCommentRepay.class);
        if(apCommentRepay!=null && dto.getOperation() ==0 ){
            // 1. 保存点赞
            //更新评论的点赞数量
            apCommentRepay.setLikes(apCommentRepay.getLikes() + 1);
            mongoTemplate.save(apCommentRepay);
            // 保存点赞数据
            //保存 APP评论信息点赞
            ApCommentRepayLike apCommentLike = new ApCommentRepayLike();
            apCommentLike.setAuthorId(user.getId());
            apCommentLike.setCommentRepayId(apCommentRepay.getId());
            apCommentLike.setOperation(dto.getOperation());
            mongoTemplate.save(apCommentLike);

        }else if(apCommentRepay!=null && dto.getOperation() == 1){
            // 2. 取消点赞
            if(apCommentRepay.getLikes()>=1){
                apCommentRepay.setLikes(apCommentRepay.getLikes() - 1);
                mongoTemplate.save(apCommentRepay);
            }
            mongoTemplate.remove(Query.query(Criteria.where("authorId").is(user.getId()).and("commentRepayId").is(apCommentRepay.getId())), ApCommentRepayLike.class);
        }
        //5.数据返回
        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("likes",apCommentRepay.getLikes());
        return ResponseResult.okResult(resultMap);
    }
}
